package com.sinba.common.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sinba.common.dto.PageDTO;
import com.sinba.common.user.dao.IUserDAO;
import com.sinba.common.user.dto.UserDTO;
import com.sinba.common.user.entity.User;

public class UserService implements IUserService{
	@Autowired
	private IUserDAO userDAO; 
	//分页
	@Transactional
	public PageDTO findPager(UserDTO qdto,String sord, String sidx){
		PageDTO p =userDAO.findPager(qdto, sord, sidx);
		List<User> userList = (List<User>) p.getData();
		List<UserDTO> userDTOList = new ArrayList<UserDTO>();
		for(User entity:userList){
			UserDTO dto = new UserDTO();
			dto.entity2dto(entity, dto);
			userDTOList.add(dto);
		}
		
		p.setData(userDTOList);
		
		return p;
	}
	//用户登录 
	@Transactional
	public boolean userLogin(UserDTO dto){
		UserDTO userDTO = new UserDTO();
		User user = userDAO.findByLoginAndPwd(dto);
		if(user!=null){
			if(StringUtils.hasText(dto.getSystemPassword())){
				userDTO.setSystemSign("YES");
			}
			userDTO.entity2dto(user, userDTO);
			HttpSession session = ServletActionContext.getRequest().getSession();
			session.setAttribute("systemUser", userDTO);
			return true;
		}else
			return false;
	};
	//保存用户
	@Transactional
	public void saveUser(UserDTO dto){
		User entity = new User();
		dto.dto2entity(dto, entity);
		userDAO.save(entity);
	};
	//删除用户
	@Transactional
	public void deleteUser(Long[] ids){
		userDAO.deleteByIds(ids);
	};
	//修改密码
	@Transactional
	public void updatePassword(UserDTO dto){
		User entity = new User();
		dto.dto2entity(dto, entity);
		userDAO.merge(entity);
	};
	@Transactional
	public UserDTO findUserInfo(Long id){
		User user = userDAO.findById(id);
		UserDTO dto = new UserDTO();
		dto.entity2dto(user, dto);
		return dto;
	}
	//登录名是否存在
	@Transactional
	public boolean loginNameExist(String loginName){
		User user = userDAO.findUniqueBy("loginName",loginName);
		if(user!=null)
			return true;
		else
			return false;
		
	}
	
}
